<template>
	<view class="content">
		<!-- 返回主页 -->
		<view class="back" @click="toindex">
			<view class="backicon"></view>
		</view>
		<view class="toptitle">
			<text style="font-size: 50rpx;">扫码签到</text>
		</view>
		<view class="mapcard">
			<view class="location-content">
				<text>当前位置:</text>
				<input type="text" disabled="true" :value="addressName" />
			</view>
			<view style="float: right;margin-top: -100rpx;margin-right: 25rpx;color: #5d5d5d;">
				<text>位置不准确？点我更新</text>
			</view>
			<view @click="refresh" class="o-icon">
				<image src="../../../static/images/png/refresh.png" style="width: 45rpx;height: 45rpx;"></image>
			</view>
			<view class="mapstyle">
				<map :show-location="true" :latitude="latitude" :longitude="longitude" type="gcj02"
					isHighAccuracy="true" class="map"></map>
			</view>
			<view style="margin-top: 20rpx;">
				<u-button text="扫码打卡" color="linear-gradient(to right, rgb(170, 170, 255), rgb(85, 85, 255))"
					shape="circle" size="large" customStyle="width: 630rpx" @click="scan"></u-button>
			</view>
		</view>
		<view class="another" v-if="isShow">
			<view style="margin-top: 10rpx;">
				<text style="color: #5d5d5d;">位置仍不精准？试试随堂拍照证明</text>
			</view>

			<view style="margin-top: 20rpx;">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" :maxCount="1"
					:previewFullImage="true"></u-upload>
			</view>
			<view style="margin-top: 20rpx;">
				<u-button text="提交" color="linear-gradient(to right, rgb(85, 85, 255), rgb(170, 170, 255))"
					shape="circle" size="large" customStyle="width: 630rpx" @click="CommitSuggest"></u-button>
			</view>

		</view>
		<view style="margin-top: 10rpx;">
			<text>{{longitude}}-{{latitude}}</text>
			<text>*进入地图等定位加载好后，点击返回键位置会自动更新</text>
		</view>
	</view>
</template>

<script>
	import amap from '@/libs/amap-wx.130.js';
	import {
		HNIT_URL,
		CLASSID,
		QRCODE_URL,
		USERNAME
	} from '../../../constants';
	export default {
		data() {
			return {
				count: 0,
				flag: false,
				amapPlugin: null,
				key: '2e676298c2ee4d0a8c6e0c8549875b0a',
				addressName: '',
				weather: {
					hasData: false,
					data: []
				},
				longitude: 0,
				latitude: 0,
				//存储每栋楼层的四个角的坐标
				locationData: {
					build1: [112.683327, 112.684325, 26.881100, 26.880483],
					build2: [112.685612, 112.686519, 26.881109, 26.880511],
					build3: [112.683434, 112.68454, 26.881684, 26.88133],
					build4: [112.685253, 112.686406, 26.881746, 26.881334],
					build5: [112.683392, 112.684325, 26.882377, 26.881885],
					build6: [112.685264, 112.686417, 26.882487, 26.881875],
					build7: [112.683531, 112.684448, 26.883196, 26.882818],
					build8: [112.685376, 112.686197, 26.883277, 26.882885],
					build9: [112.685167, 112.686294, 26.883937, 26.883923],
					build10: [112.683418, 112.684534, 26.883899, 26.883588]
				},
				user: {
					stuid: 0,
					stuname: '',
					classid: ''
				},
				picUrl: '',
				fileList1: [],
				fileurllist: [], // 存放文件的url
				newfilepath: [],
				uuid: 0,
				isShow: false,
				requestUrl: ''
			}
		},
		onLoad() {
			this.user.stuid = uni.getStorageSync("name")
			this.user.stuname = uni.getStorageSync("stuname")
			this.user.classid = uni.getStorageSync(CLASSID)
			this.picUrl = uni.getStorageSync("avatarUrl")
			this.amapPlugin = new amap.AMapWX({
				key: this.key
			});
			this.getRegeo();
		},
		methods: {
			getRegeo() {
				const _this = this
				uni.showLoading({
					title: '获取信息中'
				});
				this.amapPlugin.getRegeo({
					success: (data) => {
						_this.latitude = data[0].latitude
						_this.longitude = data[0].longitude
						this.addressName = data[0].name;
						uni.hideLoading();
					},
					fail: (res) => {}
				});

				uni.getLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: function(res) {
						const latitude = res.latitude;
						const longitude = res.longitude;
						uni.openLocation({
							latitude: latitude,
							longitude: longitude,
							success: function() {}
						});
					}
				});
				uni.hideLoading()
			},
			//扫码考勤
			scan() {
				//看之前是否扫码成功过
				if(this.flag){
					uni.showToast({
						title: "已上传证明照片，等待老师确认",
						icon: "none"
					})
				}
				const _this = this
				// 只允许通过相机扫码
				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						var classroom = res.result.split("/")[6].substring(0, 1)
						var locations = [];
						switch (classroom) {
							case '1':
								locations = _this.locationData.build1;
								break
							case '2':
								locations = _this.locationData.build2;
								break
							case '3':
								locations = _this.locationData.build3;
								break
							case '4':
								locations = _this.locationData.build4;
								break
							case '5':
								locations = _this.locationData.build5;
								break
							case '6':
								locations = _this.locationData.build6;
								break
							case '经':
								locations = _this.locationData.build8;
								break
							case '数':
								locations = _this.locationData.build10;
								break
							case '外':
								locations = _this.locationData.build7;
								break
							case '社':
								locations = _this.locationData.build9;
								break
						}
						_this.requestUrl = QRCODE_URL + res.result.substring(res.result.indexOf("jkykq"), res.result.lastIndexOf("/") + 1) +
							_this.user.stuid + "/" + _this.user.stuname + "/" + _this.user.classid
						//判断位置是否处于定位的大楼内
						//先判断二维码是否超时
						// 使用正则表达式匹配数字部分
						var beginTime = _this.requestUrl.match(/\/(\d+)\/\d+\//)[1];
						var currentTime = _this.requestUrl.match(/\/\d+\/(\d+)\//)[1];
						var now = Date.now();
						if ((now - beginTime < 360000 && now - currentTime < 15000) || (_this.longitude >=
							locations[0] && _this.longitude <= locations[1] &&
							_this.latitude <= locations[2] && _this.latitude >= locations[3])) {
							var ress = _this.requestUrl;
							_this.$request.get(ress).then(res => {
								if (res.code == 1) {
									//跳转到成功的界面
									uni.showToast({title:res.msg,icon:'none'})
								} else {
									_this.count++
									//已提交考勤记录，请找老师修改
									uni.showToast({title: res.msg,icon:'none'})
									if(_this.count == 3){
										return _this.isShow = true
									}
								}
							})
						} else {
							_this.count++
							//判断扫失败的次数
							if(_this.count == 3){
								_this.isShow = true
							}
							return wx.showToast({
								title: '二维码已失效', //提示的内容
								duration: 4000, //持续的时间
								icon: 'none'
							})
						}
					}
				});
			},
			refresh() {
				this.getRegeo()
			},
			chooseImage() {
				uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {}
				});
			},
			// 删除上传的图片
			deletePic() {
				this[`fileList1`].splice(0, 1)
				this.fileurllist[1] = ""
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length

				lists.map((item) => {
					this.fileList1.push({
						...item,
						status: 'success',
					})
				})

				for (let i = 0; i < lists.length; i++) {
					this.fileurllist.unshift(lists[i].url)
				}
			},
			// 照片上传
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: HNIT_URL + "wx/upload", // 后端api接口
						filePath: url, // uni.chooseImage函数调用后获取的本地文件路劲
						name: 'file', //后端通过'file'获取上传的文件对象
						header: {
							"Content-Type": "multipart/form-data"
						},
						success: (res) => {
							let data = JSON.parse(res.data);
							this.newfilepath.push(data.data)
							resolve(res.data)
						}
					});
				})
			},
			// 提交
			CommitSuggest() {
				//判断是否已经上传图片
				if (this.fileurllist.length == 0) {
					return wx.showToast({
						title: '请选择要上传的证明图片', //提示的内容
						duration: 4000, //持续的时间
						icon: 'none',
						mask: true //显示透明蒙层 防止触摸穿透
					})
				}
				// 上传证据照片
				for (let i = 0; i < this.fileurllist.length; i++) {
					const result = this.uploadFilePromise(this.fileurllist[i])
				}
				wx.showToast({
					title: '上传中', //提示的内容
					duration: 4000, //持续的时间
					icon: 'loading',
					mask: true //显示透明蒙层 防止触摸穿透
				})
				setTimeout(() => {
					// 发起请求
					let params = {
						picUrl: this.newfilepath
					}
					//判断是否已经进行提交
					if (this.flag) {
						uni.showToast({
							title: "已上传证明照片，等待老师确认",
							icon: "none"
						})
					} else {
						this.$request.get(this.requestUrl, params).then(res => {
							if (res.code == 1) {
								uni.showToast({
									title: "上传证明照片成功，等待老师确定",
									icon: "none"
								})
								this.flag = true
							} else {
								wx.showToast({
									title: res.msg, //提示的内容
									duration: 2000, //持续的时间
									icon: 'error',
									mask: true //显示透明蒙层 防止触摸穿透
								})
							}
						})
						this.deletePic()
						this.fileList1 = []
						this.fileurllist = []
						this.newfilepath = []
					}

				}, 1000)


			},
			toindex() {
				uni.navigateTo({
					url: "/pages/student/home/index"
				})
			}
		}
	}
</script>

<style>
	.toptitle {
		margin-top: -65rpx;
		color: #000000;
		font-size: 50rpx;
		font-family: FZSuXSLSJW;
	}

	.smbtu {
		width: 90%;
		height: 70rpx;
		border-radius: 30rpx;

	}

	.mapstyle {
		margin-top: 30rpx;
	}

	.o-icon {
		float: right;
		margin-right: 25rpx;
		margin-top: -46rpx;
	}

	.mapcard {
		width: 94%;
		background-color: white;
		height: 800rpx;
		border-radius: 40rpx;
		margin-top: 20rpx;
		box-shadow: 1px 2px 5px 2px #dadada;
	}

	.backicon {
		float: left;
		background-image: url("data:image/svg+xml,%3Csvg t='1689146294791' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='19508' width='200' height='200'%3E%3Cpath d='M501.30944 464.22016c0-19.99872-16-35.19488-35.99872-35.99872H310.4V350.62784L137.61536 464.22016l171.98592 113.59232V500.21888h155.70944c19.99872-0.79872 35.99872-16 35.99872-35.99872z' fill='%23005CFF' p-id='19509'%3E%3C/path%3E%3Cpath d='M886.38464 212.01408c0-39.46496-31.99488-71.45984-71.45984-71.45984H443.88864c-39.46496 0-71.45984 31.99488-71.45984 71.45984v117.69856a29.42464 29.42464 0 1 0 58.84928 0V225.00352a25.6 25.6 0 0 1 25.6-25.6h358.05184c2.72384 0 5.23264 0.88576 7.296 2.3552l-252.50816 91.904c-15.872 5.77536-28.74368 29.28128-28.74368 52.49536v382.88384H456.87808a25.6 25.6 0 0 1-25.6-25.6V598.7328a29.42464 29.42464 0 1 0-58.84928 0v117.69856c0 39.46496 31.99488 71.45984 71.45984 71.45984h97.08544v62.68928c0 23.21408 12.86656 37.3504 28.74368 31.57504l287.42144-104.61184c15.872-5.77536 28.74368-29.28128 28.74368-52.49536v-0.39424c0.3072-2.69824 0.50688-5.43232 0.50688-8.2176v-504.4224z' fill='%23005CFF' p-id='19510'%3E%3C/path%3E%3C/svg%3E");
		background-size: cover;
		width: 50rpx;
		height: 50rpx;
		margin-top: 6rpx;
		margin-left: 12rpx;
	}

	.back {
		float: left;
		width: 80rpx;
		margin-top: 99rpx;
		height: 58rpx;
		margin-left: -640rpx;
		border-radius: 80rpx;
		backdrop-filter: blur(5px);
		/* 设置高斯模糊效果 */
		background-color: rgba(255, 255, 255, 0.9);
		border: 1rpx #c6c6c6 solid;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.map_container {
		position: absolute;
		top: 0;
		bottom: 80px;
		left: 0;
		right: 0;
	}

	.map_text {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0px;
		height: 80px;
		background: #fff;
		padding: 0 15px;
	}

	text {
		margin: 5px 0;
		display: block;
		font-size: 12px;
	}

	.h1 {
		margin: 15px 0;
		font-size: 15px;
	}

	.map {
		width: 100%;
		height: 500rpx;
	}

	.title {
		margin-top: 5%;
		display: flex;
		justify-content: center;
	}

	.title text {
		font-size: 40rpx;
		font-weight: 900;
		color: red;
	}

	.location-content {
		/* display: flex;
		justify-content: center; */
		margin-top: 20rpx;
		margin-left: 20rpx;
	}

	.location-content text {
		font-size: 30rpx;
		color: #555555;
	}

	.location-content input {
		width: 550rpx;
		margin-left: 20rpx;
		font-size: 40rpx;
		font-weight: 600;
	}

	.another {
		/* display: flex;
		flex-direction: column; */
		width: 94%;
		background-color: white;
		height: 430rpx;
		border-radius: 40rpx;
		margin-top: 40rpx;
		box-shadow: 1px 2px 5px 2px #dadada;
	}

	.another view {
		display: flex;
		justify-content: center;
	}

	.another view text {
		font-size: 30rpx;
	}

	page {
		background-color: #f4f4f4;
	}
</style>